package com.gemini.main.counter;

import java.util.HashMap;

/**
 * com.gemini.main.counter.SynchronizedCounter
 *
 * @author zhanghailin
 */
public class SynchronizedCounter implements Counter {

    private HashMap<String, Adder> map = new HashMap<>();

    @Override
    public synchronized void save(Saver saver) {
        map.forEach((key, value)->{//因为已加锁，所以可以安全地取数据
            saver.save(key, value.like, value.comment);
        });
        map = new HashMap<>();
    }

    @Override
    public synchronized void add(String key, int like, int comment) {
        //因为已加锁，所以可以安全地更新数据
        Adder adder = map.computeIfAbsent(key, x -> new Adder());
        adder.like += like;
        adder.comment += comment;
    }
    static class Adder{
        private int like;
        private int comment;
    }
}
